﻿define(['ko', 
'utils', 
'config', 
'repositories/repository.products',
'repositories/repository.productcategories',
'router', 'viewmodels/vm.pagepath'], 
 function(ko, utils, config, repoProducts, repoProductCategories,router, vmPagePath) {
	var text = ko.observable();
	var products = ko.observableArray();
	var categoryID = 3;
	var productsTotal = ko.observableArray();
	var selectedCategory = ko.observable();
	var hoverProduct = ko.observable();
	var banner = null;
	var selectedPage;
	var CONST_NUM_ITEM_PER_PAGE = 4;
	var CONST_NUM_ITEM_PER_ROW = 3;
	var CONST_VIEW = {
		CONST_GRID: 'gridview',
		CONST_LIST: 'listview'
	};
	var productCategories = ko.observableArray();
	var productsRows = ko.observableArray();
	var view = ko.observable(CONST_VIEW.CONST_GRID);
	var pages = ko.computed(function() {
		var nProducts = productsTotal().length;
		var nPages = parseInt(nProducts / CONST_NUM_ITEM_PER_PAGE);
		if (nProducts % CONST_NUM_ITEM_PER_PAGE != 0 || nPages == 0) {
			nPages++;
		}
		var arrPages = [];
		for (var i  = 0; i< nPages; i ++){
			var page = {
				index: i+1,
				active : ko.observable(false)
			};
			if (i==0){
				page.active(true);
				selectedPage = page;
			}
			arrPages.push(page);
		}
		return arrPages;
	});
	var goNextPage = function(){
		var arrPages = pages();
		var pageIndex = selectedPage.index - 1;
		var nextPageIndex = pageIndex + 1; 
		if (nextPageIndex > arrPages.length-1){
			return false;
		}
		var nextPage = arrPages[nextPageIndex];
		onPaging(nextPage);
	};
	var goPrevPage = function(){
		var arrPages = pages();
		var pageIndex = selectedPage.index - 1;
		var nextPageIndex = pageIndex - 1; 
		if (nextPageIndex < 0){
			return false;
		}
		var nextPage = arrPages[nextPageIndex];
		onPaging(nextPage);
	};
	var onPaging = function(data, event){
		selectedPage = data;
		var arrPages = pages();
		var pageNum = data.index;
		var prePage = _.find(arrPages, function(item){
			return item.active() == true;
		});
		if(prePage){
			prePage.active(false);
		}
		data.active(true);
		getProducts({page:pageNum});
	};
	var getTotalProducts = function() {
		var self = this;
		repoProducts.getProducts({
			results : productsTotal,
		}).done(function() {
			console.log(productsTotal());
		});
	};
	var getProducts = function(inParam) {
		repoProducts.getProducts({
			results : products,
			param : inParam
		}).done(function() {
			var arrProducts = products();
			var arrProductsRow = [];
			var row = [];
			for (var i = 0; i < arrProducts.length; i++){
				if (i % CONST_NUM_ITEM_PER_ROW === 0){
					row = [];
				}
				row.push(arrProducts[i]);
				if (row.length === CONST_NUM_ITEM_PER_ROW){
					arrProductsRow.push(row);
				}
				else if (i === arrProducts.length - 1){
					arrProductsRow.push(row);
				}
			}
			productsRows(arrProductsRow);
			console.log(arrProductsRow);
		});
	};
	var getProductCategories = function(category){
		repoProductCategories.getProductCategories({
			results : productCategories
		}).done(function() {
			var selCategory = productCategories()[0].children()[0];
			if (category) {
				categoryid = category.categoryid;
				for (var i = 0; i < productCategories().length; i++){
					var categoryFound = _.find(productCategories()[i].children(), function(item){
						return item.id() === categoryid;
					});
					if(categoryFound){
						selCategory = categoryFound;
						break;
					}
				}
			}

			onCategoryClicked(selCategory);
		});
	};
	var onCategoryClicked = function(data, event){
		var categoryId = data.id();
		categoryID = categoryId;
		data.isSelected(true);
		selectedCategory(data);
		router.navigateTo(config.hashes.store + "/" + categoryId);
		getProducts({categoryid: categoryId});
	};
	selectedCategory.subscribe(function(oldValue) {
		if(oldValue){
			oldValue.isSelected(false);
		}
	}, null, "beforeChange");
	
	var loadData = function(routeData) {
		var self = this;
		getTotalProducts();
		getProductCategories(routeData);
	};
	var activate = function(routeData) {
		loadTemplate.call(this,routeData);
	};
	var loadTemplate = function(routeData) {
		var self = this;
		utils.loadTemplate(config.viewIds.store, "default/tmpl/" + config.viewTplNames.store, function() {
			bind.call(self);
		});
		loadData(routeData);
	};
	var onCheckAll = function(){
		var arrProducts = products();
		for (var i  = 0; i < arrProducts.length; i++){
			var pro =  arrProducts[i];
			var isChecked = pro.isChecked();
			pro.isChecked(!isChecked);
		}
	};
	var onProductHover = function(data, event){
		 clearTimeout(this.productMouseOverTimeoutId);
		/*
		this.productMouseOverTimeoutId = setTimeout(function(){
					 console.log('hover');
					  hoverProduct(data);
					 data.showFloat(true);
				 },100);*/
 		
 		 if(data.showFloat === true){
		 	return false;
		 }
		 hoverProduct(data);
		 data.showFloat(true);
		 event.stopPropagation();
		 return false;
	};
	 hoverProduct.subscribe(function(oldValue) {
		 if(oldValue){
			 oldValue.showFloat(false);
		}
	 }, null, "beforeChange");
	 
	var onProductMouseout = function(data, event){
		//data.showFloat(false);
		console.log('mouseout');
		event.stopPropagation();
		data.showFloat(false);
		return false;
	};
	var switchView = function(viewType){
		view(viewType);
	};
	
	var onProductMouseClicked = function(data, event){
		var url = "#/store/"+ categoryID +"/product_detail/"+ data.code();
		window.cabinetcode = data.code();
		document.cookie="cabinetName="+data.name();
		router.navigateTo(url);
	};
	
	var bind = function() {
		ko.applyBindings(this, $(config.viewIds.store).get(0));
	};
	return {
		activate : activate,
		getTotalProducts : getTotalProducts,
		products: products,
		pages: pages,
		onPaging: onPaging,
		goNextPage:goNextPage,
		goPrevPage: goPrevPage,
		onCheckAll: onCheckAll,
		productCategories: productCategories,
		productsRows: productsRows,
		switchView: switchView,
		view: view,
		onCategoryClicked: onCategoryClicked,
		onProductHover: onProductHover,
		onProductMouseout: onProductMouseout,
		onProductMouseClicked: onProductMouseClicked,
		selectedCategory: selectedCategory,
		hoverProduct: hoverProduct,
		getProductCategories: getProductCategories
	};
});
